import React from 'react'

import { connect } from 'react-redux'
import { addAction, subAction, asyncAddAction } from '../redux/actions'


class Item extends React.Component {
  render () {
    const { pname, count, add, sub } = this.props
    console.log(1111, this.props)
    return (
      <div>
        <button onClick={() => { add() }}>+</button>
        <button onClick={() => { sub() }}>-</button>
        <span>【{pname}】商品的数量【{count}】</span>
      </div>
    )
  }
}

// 回调函数=》获取store数据
const mapStateToProps = (state, ownProps) => {
  // console.log('Item', state, ownProps,)
  // 获取当前商品的数量
  return {
    count: state[ownProps.pname]
  }
}

// 回调函数=》获取store修改数据的方法
/**
 * 
 * @param {*} dispatch 修改store数据的方法
 * @param {*} ownProps 组件自身的props
 */
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    // 修改购物车商品数量加一
    add: () => dispatch(asyncAddAction(ownProps.pname)),
    // 修改购物车商品数量减一
    sub: () => dispatch(subAction(ownProps.pname))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Item)
